#include "TargetBL_Config.h"
#include "TargetBL_Interface.h"
#include "CRC.h"

//=============================================================================
// Function Definitions
//=============================================================================

//-----------------------------------------------------------------------------
// Get_Buf_CRC
//-----------------------------------------------------------------------------
//
// Return Value:  None
// Parameters:    None
//
// Returns a 16-bit CRC of the contents of a buffer.
//
//-----------------------------------------------------------------------------
U16 Get_Buf_CRC(U8 *ptr, U16 numbytes)
{
    U16 i, crc;

    crc = 0xFFFF;

    // Process each byte in the buffer into the running CRC
    for (i = 0; i < numbytes; i++)
    {
        crc = Update_CRC(crc, *ptr++);
    }

    return crc;
}

//-----------------------------------------------------------------------------
// Update_CRC
//-----------------------------------------------------------------------------
//
// Return Value:  None
// Parameters:    None
//
// This function accepts a CRC argument and a <newbyte> and returns an
// updated CRC value; Does not use a CRC Lookup Table.
//
//-----------------------------------------------------------------------------
U16 Update_CRC(U16 crc, U8 newbyte)
{
    U8 i; // loop counter

#define POLY 0x1021                    // CRC16-CCITT
    crc = crc ^ (newbyte << 8);

    for (i = 0; i < 8; i++)
    {
        if (crc & 0x8000)
        {
            crc <<= 1;
            crc ^= POLY;
        }
        else
        {
            crc <<= 1;
        }
    }
    return crc;
}
